var util = require('../../utils/util.js');
var api = require('../../config/api.js');



var app = getApp();

Page({
  data: {
      snValue:'',
      couponList:[],
      recommend_id:0,
      active:1,
  },
  onLoad: function (options) {
      let userInfo = wx.getStorageSync('userInfo');
      
        this.getCouponList();
      
  },
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
  onReady: function () {

  },

  clearSn: function(){
    this.setData({
       snValue:''
    })
  },
  goBuy:function(){
      wx.switchTab({
          url: '/pages/index/index',
      })
  },
  snInput:function(e){
      console.log(e)
      this.setData({
          snValue:e.detail.value
      })
  },
  formatCouponData:function(d){
      let _this = this;
      let couponList = [];
      d.forEach(data=>{
          if(parseInt(data.used_time) === 0){
              data.send_start_date = util.formatTime(data.send_start_date,'Y.M.D')
              data.send_end_date = util.formatTime(data.send_end_date,'Y.M.D')
              data.use_start_date = util.formatTime(data.use_start_date,'Y.M.D')
              data.use_end_date = util.formatTime(data.use_end_date,'Y.M.D')
                couponList.push(data)
            }

      })
      _this.setData({
          couponList:couponList
      })
  },
  convertCoupon:function(){

      let _this = this;
      
      let userInfo = wx.getStorageSync('userInfo');
      const {id} = userInfo || {}
      if(_this.data.snValue.length === 0){
          return false;
      }
      util.request(api.convertCoupon,{code:_this.data.snValue,userId:id},'POST').then(res=>{
          if(res.errno === 0){
            _this.formatCouponData(res.data)
          }else{
              wx.showToast({
                  title: res.errmsg

              })
          }
      })
  },
  getCouponList: function(e){
    let _this = this;
    if(e){
        _this.setData({
            active:e.currentTarget.dataset.num
        })
    }
    
    util.request(api.couponList+'?status='+_this.data.active,{},'POST').then(function(res) {
        console.log(4333,res)
        if (res.code == 200) {
            if(res.result && res.result.length>0){
                _this.setData({
                    couponList:res.result
                })
            }else{
                _this.setData({
                    couponList:[]
                })
            }
            
        }
    });
  },
  onShow: function () {

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {

    // 页面关闭
  }
})